package com.yc.mvc;

import com.yc.mvc.web.MyDispatchServlet;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.http.HttpServlet;

//public class MyWebApplicationInitializer extends AbstractDispatcherServletInitializer {
//    @Override
//    protected WebApplicationContext createRootApplicationContext() {
//        return null;
//    }
//    @Override
//    protected WebApplicationContext createServletApplicationContext() {
//        AnnotationConfigWebApplicationContext cxt = new AnnotationConfigWebApplicationContext();
//        cxt.register(MvcConfig.class);
//        return cxt;
//    }
//    @Override
//    protected String[] getServletMappings() {
//        return new String[] { "/" };
//    }
//}

public class MyWebApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(javax.servlet.ServletContext servletContext)
            throws ServletException {
        // 加载 Spring 配置
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MvcConfig.class);
        // 注册转发器Servlet
        HttpServlet servlet = new MyDispatchServlet();//DispatcherServlet(context);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        // 设置服务器在启动时加载 DispatcherServlet
        registration.setLoadOnStartup(1);
        // 转发全部请求，必须配置响应地址为：/
        registration.addMapping("/");

        // 添加文件上传配置
        MultipartConfigElement mc = new MultipartConfigElement("/");
        registration.setMultipartConfig(mc);
    }
}
